<template>
    <Card :bordered="true" class="event-report" id="report-view">
        <Row type="flex" justify="space-between" class="code-row-bg">
            <Col span="8">
                <DatePicker type="daterange" format="yyyy-MM-dd" @change="changeDate" :options="dateOptions" v-model:value="dateValue"  placeholder="选择日期" style="width:100%;"></DatePicker>
            </Col>
            <!-- <Col :span="flexNum">
                <Select v-model="time.unit" placeholder="时间周期">
                    <Option v-for="item in timeUnits" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </Col> -->
            <!-- <Col :span="flexNum" v-if="time.unit != 'none'">
                 <Select v-model="indicator" placeholder="选择指标">
                    <Option v-for="item in indicators" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </Col> -->
            <!-- <Col :span="flexNum" v-if="time.unit != 'none'">
                <Select v-model="dimension" placeholder="显示分组" multiple :max-tag-count="0" :max-tag-placeholder="showDimensionLabel">
                    <Option v-for="item in groups" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </Col> -->
            <Col span="4">
                <Select v-model="chartType" placeholder="图标类型" >
                    <Option v-for="item in chartTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </Col>
        </Row>
        <Row class="chart">
            <Col span="24">
                <Spin v-if="loading" fix>
                    <Icon type="ios-loading" size=24 class="demo-spin-icon-load"></Icon>
                    <div>加载中...</div>
                </Spin>
                <div :id="`myCharts`+chartconfig.id" class="echarts"></div>
            </Col>
        </Row>
    </Card>
    
</template>

<script>
    import ElementResize from '../../../../components/ElementResize'
    export default {
        name: "EventReport",
        props: {
            events: Array,
            properties: Array,
            measures: Array,
            chartconfig:Object,
            base:null,
        },
        data: function() {
            return {
                // flexNum:'6',
                timeUnits: [
                    {
                        label: '无时间分组',
                        value: 'none'
                    },
                    {
                        label: '按天',
                        value: 'day'
                    },
                    {
                        label: '按周',
                        value: 'week'
                    },
                    {
                        label: '按月',
                        value: 'month'
                    }
                ],
                loading: true,
                time: {
                    start: this.$sessionStore.getDay(-7),
                    end: new Date().toLocaleDateString('cn',{year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g,'-'),
                    unit: 'none',
                },
                dateValue: [this.$sessionStore.getDay(-7),this.$sessionStore.getDay(0)],
                indicator: '',
                dimension: [],
                chartType: 'line',
                chart: {
                    eventChart: null,
                    options: {
                        title: {
                            text: ''
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        grid: {
                            left: '0%',
                            right: '3%',
                            containLabel: true
                        },
                        legend: {
                            data:[]
                        },
                        toolbox: {
                            feature: {
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: []
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: []
                    },
                },
                table: {
                    columns: [],
                },
                resultSet: [],
                chartTypes: [{
                    label: '柱状图',
                    value: 'bar'
                }, {
                    label: '折线图',
                    value: 'line'
                }],
                dateOptions: {
                    shortcuts: [
                        {
                            text: '今天',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                return [start, end];
                            }
                        },
                        {
                            text: '昨天',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24);
                                return [start, end];
                            }
                        },
                        {
                            text: '最近7天',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                return [start, end];
                            }
                        },
                        {
                            text: '最近一月',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                return [start, end];
                            }
                        },
                        {
                            text: '最近三月',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                return [start, end];
                            }
                        }
                    ]
                },
            };

        },
        computed: {
            propertyMap: function() {
                let propertyMap = {};
                for(let i = 0; i < this.properties.length; i++) {
                    propertyMap[this.properties[i].name] = this.properties[i];
                }
                return propertyMap;
            },
            eventMap: function() {
                let eventMap = {};
                for(let i = 0; i < this.events.length; i++) {
                    eventMap[this.events[i].name] = this.events[i];
                }
                return eventMap;
            },
            measureMap: function() {
                let measureMap = {};
                for(let i = 0; i < this.measures.length; i++) {
                    measureMap[this.measures[i].name] = this.measures[i];
                }
                return measureMap;
            },
            indicators: function() {
                let indicators = [];
                let obj = {};
                let config = eval('(' +this.chartconfig.customReport.config+ ')');
                for(let i = 0; i < config.indicators.length; i++) {
                    for(let j = 0; j < config.indicators[i].measure.length; j++) {
                        let eventName = config.indicators[i].event;
                        let measureName = config.indicators[i].measure[j].name;
                        if(!obj[eventName + "_" + measureName]) {
                            if(eventName in this.eventMap && measureName in this.measureMap) {
                                indicators.push({
                                    label: this.eventMap[eventName].displayName + "的" + this.measureMap[measureName].displayName,
                                    value: eventName + "_" + measureName
                                });
                                obj[eventName + "_" + measureName] = true;
                            }

                        }
                    }
                }
                return indicators;
            },
            groups: function() {
                let groups = [];
                let obj = {};
                let config = eval('(' +this.chartconfig.customReport.config+ ')');
                for(let i = 0; i < this.resultSet.length; i++) {
                    let label = "";
                    for(let j = 0; j < config.dimensions.length; j++) {
                        if(j === config.dimensions.length - 1){
                            label += this.resultSet[i][config.dimensions[j]];
                        } else {
                            label += this.resultSet[i][config.dimensions[j]]+",";
                        }
                    }
                    if(!obj[label]) {
                        groups.push({
                            label: label,
                            value: label
                        });
                        obj[label] = true;
                    }

                }
                return groups;

            },
           
        },
        methods: {
            showDimensionLabel: function(hiddenTags) {
                return "显示分组";
            },
            changeDate: function(dateValue) {
                this.time.start = dateValue[0];
                this.time.end = dateValue[1];
            },
            showData: function() {
                this.query();
            },
            query: function() {
                let _that = this;
                _that.loading = true;
                let config = eval('(' +this.chartconfig.customReport.config+ ')');
                if(_that.chartconfig.customReport.base == 0){
                    _that.$axios.post(_that.$api.report + "/analysis/event",
                    {
                        time: _that.time,
                        config: config
                    },
                    {
                        headers: {
                            "Authorization": "Bearer "+_that.$sessionStore.fetch(),
                            "Accept": "application/json"
                        },
                        params: {
                            projectId: _that.$store.state.projectId
                        }
                    }).then(response => {
                        if (response.status === 200) {
                            _that.resultSet = response.data;
                            _that.updateChart();
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    }).finally(() => {
                        _that.loading = false;
                    });
                }else if(_that.chartconfig.customReport.base == 1){
                    this.$axios.post(_that.$api.report + "/analysis/ad",
                    {
                        time: _that.time,
                        config: config
                    },
                    {
                        headers: {
                            "Authorization": "Bearer "+_that.$sessionStore.fetch(),
                            "Accept": "application/json"
                        },
                        params: {
                            projectId: _that.$store.state.projectId
                        }
                    }).then(response => {
                        if (response.status === 200) {
                            _that.resultSet = response.data;
                            _that.updateChart();
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    }).finally(() => {
                        _that.loading = false;
                    });
                }
            },
            updateChart: function() {
                let options = {
                    title: {
                        text: ''
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:[]
                    },
                    grid: {
                        left: '0%',
                        right: '3%',
                        bottom:'3%',
                        top:'10%',
                        containLabel: true
                    },
                    toolbox: {
                        feature: {
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: []
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [],
                };
                let obj = {};
                let config = eval('(' +this.chartconfig.customReport.config+ ')');

                if(this.time.unit == 'none'){
                    for(let index = 0; index < this.indicators.length; index++) {
                        options.legend.data.push(this.indicators[index].label);
                        let seriesData = [];
                        for(let i = 0; i < this.resultSet.length; i++) {
                            let label = "";
                            for (let j = 0; j < config.dimensions.length; j++) {
                                if (j === config.dimensions.length - 1) {
                                    label += this.resultSet[i][config.dimensions[j]];
                                } else {
                                    label += this.resultSet[i][config.dimensions[j]] + ",";
                                }
                            }
                            if(!obj[label]) {
                                options.xAxis.data.push(label);
                                obj[label] = true;
                            }
                            seriesData.push(this.resultSet[i][this.indicators[index].value]);
                        }
                        options.series.push({
                            name: this.indicators[index].label,
                            type: this.chartType,
                            smooth: true,
                            data: seriesData
                        });
                    }
                }else{
                    for(let index = 0; index < this.dimension.length; index++) {
                        options.legend.data.push(this.dimension[index]);
                        let seriesData = [];
                        for(let i = 0; i < this.resultSet.length; i++) {
                            let label = "";
                            for (let j = 0; j < config.dimensions.length; j++) {
                                if (j === config.dimensions.length - 1) {
                                    label += this.resultSet[i][config.dimensions[j]];
                                } else {
                                    label += this.resultSet[i][config.dimensions[j]] + ",";
                                }
                            }
                            if (this.dimension[index] === label) {
                                if(!obj[this.resultSet[i].date]) {
                                    options.xAxis.data.push(this.resultSet[i].date);
                                    obj[this.resultSet[i].date] = true;
                                }
                                seriesData.push(this.resultSet[i][this.indicator]);
                            }
                        }
                        options.series.push({
                            name: this.dimension[index],
                            type: this.chartType,
                            smooth: true,
                            data: seriesData
                        });
                    }
                }
                this.chart.eventChart.setOption(options, true);
            }
        },
        mounted: function() {

            let $echartsDOM = document.getElementById('myCharts'+this.chartconfig.id)
            let myCharts = this.$echarts.init($echartsDOM,'light');
            this.chart.eventChart = this.$echarts.init(myCharts._zr.dom, 'light');
            this.chart.eventChart.setOption(this.chart.options, true);
            this.query();
            ElementResize.on(document.getElementById('report-view'), () => {
               this.chart.eventChart.resize();
            });
            if(this.indicators.length > 0) {
                this.indicator = this.indicators[0].value;
            }
        },
        watch: {
            indicators: function() {
                if(this.indicators.length > 0) {
                    this.indicator = this.indicators[0].value;
                }
            },
            groups: function() {
                if(this.groups.length > 0) {
                    this.dimension.splice(0, this.dimension.length);
                    for(let i = 0; i < Math.min(10, this.groups.length); i++) {
                        this.dimension.push(this.groups[i].value);
                    }
                }
            },
            time:{
                handler(newdate,olddate){
                    this.showData();
                    // 控制选择控件的宽度
                    // newdate.unit != 'none'? this.flexNum = '4' : this.flexNum = '6'
                },
                deep:true
            },
            indicator: function() {
                this.updateChart();
            },
            dimension: function() {
                this.updateChart();
            },
            chartType: function() {
                this.updateChart();
            },
        }
    }
</script>

<style scoped>
    .event-report {
        padding: 0px;
        margin: 0px;
        border: none;
    }
    .filters {
        margin-bottom: 10px;
    }
    .table-actions {
        margin-bottom: 10px;
    }
    .echarts {
        width: 100%;
        height: 363px;
    }
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .demo-spin-col{
        height: 100px;
        position: relative;
    }
</style>